/**
 * 
 */
package com.dhcc.cdbp.query;

import static org.junit.Assert.*;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.BytesRef;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * TermRangeQuery:术语范围查询，用于字符串范围查询
 * 		既然涉及到范围必然需要字符串比较大小，字符串比较大小其实比较的是ASC码值，即ASC码范围查询。
 * 		一般对于英文来说，进行ASC范围查询还有那么一点意义，中文汉字就没有什么太多的意义了，所以这个
 * TermRangeQuery了解就行，用途不大。
 * @author 谢进军
 *
 */
public class TermRangeQueryTest {
	private static final String directoryPath = "src/main/resources/lucenedir";
	private static final String fieldName = "contents";
	private static String lowerTermString = "a";  
	private static String upperTermString = "z";
	@Before
	public void setUp() throws Exception {
	}
	@Test
	public void test() throws IOException {
		List<Document> result = new ArrayList<>();
		Directory dic = FSDirectory.open(Paths.get(directoryPath));
		IndexReader reader = DirectoryReader.open(dic);
		IndexSearcher searcher = new IndexSearcher(reader);
		
		Query query = new TermRangeQuery(fieldName, new BytesRef(lowerTermString), new BytesRef(upperTermString), false, false);
		TopDocs docs = searcher.search(query, Integer.MAX_VALUE);
		ScoreDoc[] hits = docs.scoreDocs;
		for (ScoreDoc doc : hits) {
			int docId = doc.doc;
			Document document = searcher.doc(docId);
			result.add(document);
		}
		
		for( Document document : result){
			System.out.println(document.toString());
		}
	}
	@After
	public void tearDown() throws Exception {
	}
}
